(function() {
	var pagestack = [];
	var lastHash = [];
	var targetPage = "";
	var lastPage = "";
	var j = 0;
	var checkMoveTab = false;

	// alert(navigator.userAgent.match(/android/i));
	// alert(navigator.userAgent.indexOf("4.0.") != -1);
	// alert(!navigator.userAgent.match(/mobile/i));
	// alert(((navigator.userAgent.match(/android/i) &&
	// (navigator.userAgent.indexOf("4.0.") != -1) ||
	// !navigator.userAgent.match(/mobile/i))));
//	onpopstate = function(e) {
//		var backCheck = false;
//		try {
//			if (pagestack.length > 0) {
//				$("[data-role='page']").live("pageshow", function() {
//					var nowPage = $(this).attr("id");
//					for ( var i = pagestack.length; i--;) {
//						if ((targetPage === undefined || targetPage === nowPage) && nowPage === pagestack[i].page) {
//							for ( var j = pagestack.length - 1, min = i; j > min; j--) {
//								var now_page = $('#' + pagestack[j].page);
//								now_page.remove();
//								lastHash.push(pagestack.pop());
//							}
//							backCheck = true;
//							break;
//						}
//					}
//					if (!backCheck && lastHash.length === 0) {
//						pagestack.push({
//							page : targetPage
//						});
//					} else if (!backCheck && targetPage) {
//						pagestack.push({
//							page : targetPage
//						});
//						lastHash = [];
//					} else if (!backCheck && lastHash.length > 0) {
//						pagestack.push(lastHash.pop());
//					}
//					
//					if(backCheck){
//						$(this).trigger("reStartPage");
//					}
//					else {
//						$(this).trigger("startPage");
//					}
//					targetPage = undefined;
//				});
//			} else {
//				pagestack.push({
//					page : $("[data-role=page]")[0].id
//				});
//				targetPage = $("[data-role=page]")[0].id;
//			}
//		} catch (e) {
//			console.log(e.stack)
//		}
//	}

	$("[data-role='page']").live("pageshow", function () {
		if(checkMoveTab) {
			checkMoveTab = false;
			$(this).trigger("startPage");
			return false;
		}
		var backCheck = false;
		try {
			if (pagestack.length > 0) {
					var nowPage = $(this).attr("id");
					for ( var i = pagestack.length; i--;) {
						if ((targetPage === undefined || targetPage === nowPage) && nowPage === pagestack[i].page) {
							for ( var j = pagestack.length - 1, min = i; j > min; j--) {
								var now_page = $('#' + pagestack[j].page);
								now_page.remove();
								lastHash.push(pagestack.pop());
							}
							backCheck = true;
							break;
						}
					}
					if (!backCheck && lastHash.length === 0) {
						pagestack.push({
							page : targetPage
						});
					} else if (!backCheck && targetPage) {
						pagestack.push({
							page : targetPage
						});
						lastHash = [];
					} else if (!backCheck && lastHash.length > 0) {
						pagestack.push(lastHash.pop());
					}

					var data = $.data(document, "Data");
					if (backCheck) {
						$(this).trigger("reStartPage", [ (data) ? data.data : undefined, lastPage ]);
					} else {
						$(this).trigger("startPage", (data) ? [ data.data, data.prevPageId ] : undefined);
					}

					$.removeData(document, "Data");
					lastPage = nowPage;
					targetPage = undefined;
			} else {
				pagestack.push({
					page : $("[data-role=page]")[0].id
				});
				targetPage = $("[data-role=page]")[0].id;
				
				$(this).trigger("startPage");
			}
		} catch (e) {
			console.log(e.stack)
		}
	});

	$.mobile.isMobile = function() {
		if (navigator.userAgent.match(/iPhone|iPod|Android|Windows CE|BlackBerry|Symbian|Windows Phone|webOS|Opera Mini|Opera Mobi|POLARIS|IEMobile|lgtelecom|nokia|SonyEricsson/i) != null || navigator.userAgent.match(/LG|SAMSUNG|Samsung/) != null) {
			return true;
		} else {
			return false;
		}
	}

	var loadScript = function(page) {

		var dfd = $.Deferred();

//		if (((navigator.userAgent.match(/android/i) && ((navigator.userAgent.indexOf("4.0.") != -1) ) || !navigator.userAgent.match(/mobile/i)))) {
		if (!navigator.userAgent.match(/mobile/i)) {
			dfd.resolve();
			return dfd;
		}

		var cPath = location.href, path = cPath.substring(cPath.lastIndexOf("www") + 4, cPath.length), depth = path.split("/").length - 1, dir_prefix = "", ii = 0,
			pre_path = cPath.substring(0, cPath.lastIndexOf("www") + 4);

		for (; ii < depth; ii++) {
			dir_prefix += "../";
		}

		var loc_info = getPositionForPage(page);
		var scriptUrl = pre_path + loc_info + "js/" + getIdForPage(page) + ".js";
		var checkScript = true;

		$("head script").each(function(a, b) {
			if ($(b).attr("src") === scriptUrl) {
				checkScript = false;
			}
		});

		if (checkScript) {
			var head = document.getElementsByTagName("head")[0];
			script = document.createElement('script');
			script.type = 'text/javascript';
			script.src = scriptUrl;

			if (script.readyState) {
				script.onreadystatechange = function() {
					if (script.readyState === "loaded" || script.readyState === "complete") {
						script.onreadystatechange = null;
						if (script.status === 200) {
							dfd.resolve();
						} else {
							alert("해당 위치에 js 폴더가 없거나 js파일이 없습니다.\n 확인해주세요.");
							dfd.resolve();
						}
					}
				}
			} else {
				script.onload = function() {
					dfd.resolve();
				};
				script.onerror = function(e) {
					alert("해당 위치에 js 폴더가 없거나 js파일이 없습니다.\n 확인해주세요.");
					dfd.resolve();
				}
			}
			head.appendChild(script);
		} else {
			dfd.resolve();
		}

		return dfd;
	}

	var getIdForPage = function(page) {
		return page.split("/").pop().split(".")[0];
	}

	var getPositionForPage = function(page) {
		var position = page.split("/");
		var result = "";
		if (position.length > 1) {
			for ( var i = 0, max = position.length - 1; i < max; i++) {
				result += position[i] + "/";
			}
			return result;
		} else {
			return "";
		}
	}

	// 기타 탭 이동 함수
	$.mobile.moveTab = function(page) {
		var cPath = location.href, path = cPath.substring(cPath.lastIndexOf("www") + 4, cPath.length), depth = path.split("/").length - 1, dir_prefix = "", ii = 0;
		var htmlName = page.split("/");
		
		for (; ii < depth; ii++) {
			dir_prefix += "../";
		}
		
		loadScript(page).done(function() {
			checkMoveTab = true;
			$.mobile.changePage(dir_prefix + page, {
				changeHash : false
			});
			pagestack[pagestack.length - 1] = {
				page : getIdForPage(page)
			};
			var state = {
				hash : "#/" + $.mobile.path.get(location.href).replace("file:///", "") + page,
				title : "공간 조회",
				initialHref : $.mobile.path.get(location.href) + page
			}
			window.history.replaceState(state, getIdForPage(page), page);
		});
	};

	// 기타 페이지 이동 함수
	$.mobile.movePage = function(page, data) {
		var cPath = location.href, path = cPath.substring(cPath.lastIndexOf("www") + 4, cPath.length), depth = path.split("/").length - 1, dir_prefix = "", ii = 0;

		for (; ii < depth; ii++) {
			dir_prefix += "../";
		}
		
		var backCheck = false;
		var step = 0;
		var htmlName = page.split("/");
		var stack = {
			page : htmlName[htmlName.length - 1].split(".")[0]
		}

		for ( var i = pagestack.length; i--;) {
			if (pagestack[i].page === stack.page) {
				backCheck = true;
				step = -(pagestack.length - i - 1);
			}
		}

		targetPage = htmlName[htmlName.length - 1].split(".")[0];

		$.data(document, "Data", {
			"data" : data,
			"prevPageId" : $("[data-role='page'].ui-page-active").attr("id")
		});
		if (backCheck) {
			history.go(step);
		} else {
			loadScript(page).done(function() {
				$.mobile.changePage(dir_prefix + page);
			});
		}
	};

	$.mobile.moveBack = function(data, depth) {
		$.data(document, "Data", {
			"data" : data,
			"prevPageId" : $("[data-role='page'].ui-page-active").attr("id")
		});
		if (depth) {
			if (depth > pagestack.length) {
				console.log("moveBack의 depth수치가 잘못되었습니다. 수정 바랍니다.");
				return false;
			}
			history.go("-" + depth);
		} else {
			history.back();
		}
	}

	// 리스트 추가
	$.setList = function(option) {
		return (function(data_set) {
			var template, targets, data_format, max, i, html_string;
			template = option.template.clone();
			targets = {};
			targets = option.target(template);
			content = option.content;
			data_format = option.data;
			max = data_set.length;
			html_string = "";
			for (i = 0; i < max; i++) {
				data_format(targets, data_set[i]);
				html_string += template.html();
			}
			content.append(html_string);
			if (option.onAddsFinish) {
				option.onAddsFinish();
			}
		});
	}

	// 리스트 추가
	$.fn.onList = function(context, param) {
		return this.each(function() {
			if (context === "setList") {
				if (!this.opts) {
					alert("리스트 초기화가 되어 있지 않습니다.\n리스트 초기화를 먼저 해주세요.");
					return false;
				}
				var data_set = param;
				var template, targets, data_format, max, i, html_string;
				template = this.template;
				targets = {};
				targets = this.targets;
				content = this.content;
				data_format = this.data_format;
				max = data_set.length;
				html_string = "";
				for (i = 0; i < max; i++) {
					data_format(targets, data_set[i]);
					html_string += template.html();
				}
				content.append(html_string);
				if (this.opts.onAddsFinish) {
					this.opts.onAddsFinish();
				}
			} else if (context === "makeList") {
				var option = param;
				this.opts = option;
				this.template = option.template.clone();
				this.targets = option.target(this.template);
				this.content = $(this);
				this.data_format = option.data;
			}
		});
	};
	
	// atap 트리거 이벤트
	var posible_tap = "on";
	var event_page = "";
	var event_target;
	var set_posible_tap;
	var timer;

	if ($.mobile.isMobile()) {
		$("[data-role=page]").live("click", function(e) {
			if (e.target.type === "checkbox") {
				$.noop();
			} else {
				e.stopPropagation();
				e.preventDefault();
			}
		});
	}
	$("[data-role=page]").live("tap", function(e) {
		if (posible_tap === "on") {
			$(e.target).trigger("atap");
			event_page = this.id;
			event_target = e.target;
			posible_tap = "off";
			set_posible_tap = setTimeout(function() {
				posible_tap = "on";
			}, 100);
		} else if (event_page === this.id && event_target !== e.target) {
			if (posible_tap === "off") {
				$(e.target).trigger("atap");
				clearTimeout(set_posible_tap);
				event_target = e.target;
				posible_tap = "pause";
				set_posible_tap = setTimeout(function() {
					posible_tap = "on";
				}, 100);
			}
		}

	});

	var setRollOverClsName = function($dom) {
		return $dom.attr("data-rollover-name") || $dom.attr("id");
	}

	var addRollOverEvent = function() {
		var supportTouch = ("ontouchend" in document && $.mobile.isMobile()), touchStartEvent = supportTouch ? "touchstart" : "mousedown", touchStopEvent = supportTouch ? "touchend" : "mouseup", touchMoveEvent = supportTouch ? "touchmove" : "mousemove";
		var eventSet = "touchstart touchend touchmove mousedown mouseup mousemove mouseenter vmouseup";
		$(document).on(eventSet, "select[data-rollover='true']", function (event) {
			var $dom = $(this), evt = event.type, clsname, hov;
			if ($dom.length) {
				clsname = setRollOverClsName($dom) + "_hover";
				$dom = $dom.parent();
				if (evt === touchStartEvent) {
					$dom.addClass(clsname);
				} else if (evt === touchStopEvent || evt === touchMoveEvent || evt === "vmouseup") {
					$dom.removeClass(clsname);
				}
			}
		});
		$(document).on(eventSet, "a[data-rollover='true']", function (event) {
			var $dom = $(this), evt = event.type, clsname, hov;
			if ($dom.length) {
				clsname = setRollOverClsName($dom) + "_hover";
				if (evt === touchStartEvent) {
					$dom.addClass(clsname);
				} else if (evt === touchStopEvent || evt === touchMoveEvent || evt === "vmouseup") {
					$dom.removeClass(clsname);
				}
			}
		});
	}();
})();